import React from 'react';
import { useAuth } from "context/auth-context";
import { Form, Button, Input, Card } from 'antd';
import { LongButton } from 'unauthenticated-app';
import { useAsync } from 'views/utils/use-async';

export const RegisterView = ({onError} : {onError: (error:Error) => void}) => {
    const { register } = useAuth()
    const { run, isLoading } = useAsync(undefined,{throwOnError:true})

    const handleSubmit = async ({checkPassword,...values} : { username:string, password:string, checkPassword:string}) => {
        console.log(values)
        if(checkPassword !== values.password) {
            onError(new Error('请确认密码！'))
            return
        }
        
        try {
            await run(register(values))
        } catch (e) {
            onError(e as Error)
        }
    }

    return  <Form onFinish={handleSubmit}>
                <Form.Item
                    name={'username'}
                    rules={[{ required: true, message: '请输入用户名!' }]}>
                    <Input placeholder='用户名' />
                </Form.Item>
                <Form.Item
                    name={'password'}
                    rules={[{ required: true, message: '请输入密码!' }]}>
                    <Input.Password placeholder='密码'/>
                </Form.Item>
                <Form.Item
                    name={'checkPassword'}
                    rules={[{ required: true, message: '请确认密码!' }]}>
                    <Input.Password placeholder='确认密码'/>
                </Form.Item>
                <Form.Item>
                    <LongButton loading={isLoading} type="primary" htmlType="submit">注册</LongButton>
                </Form.Item>
            </Form>
}
